<?php
/**
 * 新浪微博认证授权类
 * @author shallker.wang@profero.com
 * @date  2012.07.31
 */
require_once APPPATH.'libraries/sina_weibo/app_config.php';
require_once APPPATH.'libraries/sina_weibo/saetv2.ex.class.php';

class Weibo_auth {
    
    var $app_key;
    var $app_secret_key;
    var $app_callback;
    
    var $oAuth2;
    var $auth_url;
    
    var $code;
    var $access_token;
    
    function __construct() {
        $this->app_key = WB_AKEY;
        $this->app_secret_key = WB_SKEY;
        $this->app_callback = WB_CALLBACK_URL;
        $this->oAuth2 = new SaeTOAuthV2($this->app_key, $this->app_secret_key);
        $this->auth_url = $this->oAuth2->getAuthorizeURL($this->app_callback);
    }
    
    public function get_access_token($code) {
        $params = array();
        $params['code'] = $code;
        $params['redirect_uri'] = $this->app_callback;
        $this->code = $code;
        $this->access_token = $this->oAuth2->getAccessToken('code', $params);
        if (isset($this->access_token['error'])) {
            throw new Exception($this->access_token['error']);
        }
        return $this->access_token;
    }
    
    public function get_auth_url($scope=null, $with_offical=0) {
        //'&with_offical_account=1&scope=follow_app_official_microblog'
        $url = $this->oAuth2->getAuthorizeURL($this->app_callback);
        if ($scope) {
            if ($scope == 'all') {
                $url .= '&scope=friendships_groups_read,friendships_groups_write,statuses_to_me_read,follow_app_official_microblog';
            } else {
                $url .= "&scope={$scope}";
            }
        }
        if ($with_offical) {
            $url .= '&with_offical_account=1';
        }
        return $url;
    }
}
